package com.xiangyu.demo.interceptor;

import com.xiangyu.demo.utils.VerifyHandler;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * java类简单作用描述
 *
 * @ProjectName: springboot-demo
 * @Package: com.xiangyu.demo.interceptor
 * @Description: java类作用描述
 * @Author: 向羽
 * @CreateDate: 2018/1/19 14:36
 * @UpdateUser: 向羽
 * @UpdateDate: 2018/1/19 14:36
 * @UpdateRemark: The modified content
 * @Version: 2.0
 */
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
//        System.out.println(">>>MyInterceptor1>>>>>>>在请求处理之前进行调用（Controller方法调用之前）");
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //获得对应的方法
        Method method = handlerMethod.getMethod();
        System.out.println("method=====>"+method.getName());
        VerifyHandler verifyHandler = method.getAnnotation(VerifyHandler.class);
        if (verifyHandler!=null){
            if (verifyHandler.isAuth()){
                if ("pc".equalsIgnoreCase(httpServletRequest.getHeader("dev"))){
                    return true;
                }else {
                    httpServletResponse.sendError(HttpStatus.UNAUTHORIZED.value(),"用户登入失效！");
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println(">>>MyInterceptor1>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println(">>>MyInterceptor1>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
    }
}
